package org.iabako.server.serviceimpl.business;

import org.iabako.server.dao.business.ProductDAO;
import org.iabako.server.dao.business.ServiceDAO;
import org.iabako.shared.dto.SuggestItemDTO;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.iservice.business.ProductAndServiceService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jose on 19/01/15.
 */
@org.springframework.stereotype.Service("productAndServiceService")
public class ProductAndServiceServiceImpl implements ProductAndServiceService {


    @Autowired
    ProductDAO productDAO;

    @Autowired
    ServiceDAO serviceDAO;

    public List<SuggestItemDTO> getSuggestions(String req) {
        List<SuggestItemDTO> suggestions = new ArrayList<SuggestItemDTO>(10);

        List<Object[]> results = productDAO.getNamesBySuggestion(req);
        for (Object[] result : results) {
            suggestions.add(new SuggestItemDTO("product_" + result[0], (String) result[1], (String) result[2], null, null));
        }

        results = serviceDAO.getNamesBySuggestion(req);
        for (Object[] result : results) {
            suggestions.add(new SuggestItemDTO("service_" + result[0], (String) result[1], (String) result[2], null, null));
        }

        return suggestions;
    }

    public AbstractEntity getByHiddenSelectionCode(String hiddenSelectionCode) {
        if (hiddenSelectionCode.contains("product_")) {
            return productDAO.findById(Long.parseLong(hiddenSelectionCode.replace("product_", "")));
        } else {
            return serviceDAO.findById(Long.parseLong(hiddenSelectionCode.replace("service_", "")));
        }
    }
}
